package com.zoe.thread.th18_completefuture;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.thread.ThreadUtil;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;

/**
 * @author zoe.Zhang
 * @date 2022/06/28
 * @description
 */
public class CompleteFutureCountDownLatch {

    public static void main(String[] args) throws Exception {
        ExecutorService executor = ThreadUtil.newExecutor(1);
        List<Integer> st = CollUtil.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
        TimeInterval timer = DateUtil.timer();
        timer.start();
        CountDownLatch countDownLatch = ThreadUtil.newCountDownLatch(st.size());
        for (Integer integer : st) {
            executor.execute(() -> {
                try {
                    ThreadUtil.sleep(1 * 1000); // 线程睡眠 1 秒
                    System.out.println(integer);
                }
                finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        long l = timer.intervalSecond();
        System.out.println("耗费时间:" + l);
        System.out.println("==============CompletableFuture");
        timer.restart();
        CompletableFuture[] completableFutures = st.stream()
                                                   .map(t -> CompletableFuture.supplyAsync(() -> {
                                                       ThreadUtil.sleep(1000);
                                                       // if (t == 5) {
                                                       //     throw new RuntimeException("运行时异常");
                                                       // }
                                                       return t;
                                                   }, executor)
                                                                              .whenComplete((res, e) -> System.out.println(res + "===" + e)))
                                                   .toArray(CompletableFuture[]::new);
        CompletableFuture.allOf(completableFutures).exceptionally(e -> {
            System.out.println("====");
            throw new RuntimeException(e);
        });
        long l1 = timer.intervalSecond();
        System.out.println("耗费时间:" + l1);
    }
}
